from django.http import JsonResponse
from django.db.models import Count
from django.views.decorators.http import require_http_methods
from ..models import Question, Subject

@require_http_methods(["GET"])
def get_subject_question_stats(request, subject_id):
    """获取指定科目的题目统计信息"""
    try:
        # 验证科目是否存在
        subject = Subject.objects.get(id=subject_id)

        # 获取该科目下各类型题目的数量
        stats = Question.objects.filter(subject_id=subject_id)\
            .values('question_type')\
            .annotate(count=Count('id'))

        # 将结果转换为更友好的格式
        result = {
            'subject_name': subject.name,
            'single_choice': 0,
            'multiple_choice': 0,
            'judge': 0
        }

        # 填充统计数据
        for stat in stats:
            if stat['question_type'] == 'single':
                result['single_choice'] = stat['count']
            elif stat['question_type'] == 'multiple':
                result['multiple_choice'] = stat['count']
            elif stat['question_type'] == 'judge':
                result['judge'] = stat['count']

        return JsonResponse({
            'status': 'success',
            'data': result
        })

    except Subject.DoesNotExist:
        return JsonResponse({
            'status': 'error',
            'message': '科目不存在'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': str(e)
        }, status=500)